<?php
/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: dzf_base_request.php 1914 2013-08-26 03:16:11Z laoguozhang $
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class dzf_base_request extends dzf_base_class
{	
	protected $_port = null;

	protected $_hostInfo = null;

	protected $_clientIp = null;

	protected $_language = null;

	protected $_pathInfo = null;
	
	protected $_attribute = array();

	private $_scriptUrl = null;
	
	private $_requestUri = null;
	
	private $_baseUrl = null;
	
	private $_mobile = null;
	
	private $_ajax = null;
	
	public function get($k = null, $type = '', $default = null) {
		return $this->_val($_GET, $k, $type, $default);
	}

	public function get_int($k, $default = null) {
		return $this->get($k, 'd', $default);
	}


	public function get_string($k, $default = null) {
		return $this->get($k, 's', $default);
	}

	public function post($k = null, $type = '', $default = null) {
		return $this->_val($_POST, $k, $type, $default);
	}
	
	public function post_int($k, $default = null) {
		return $this->post($k, 'd', $default);
	}


	public function post_string($k, $default = null) {
		return $this->post($k, 's', $default);
	}
	
	protected function _val($source, $k = null, $type = 0, $default = null) {
		if(!isset($k)) {
			return $source;
		}
		if(isset($source[$k])) {
			switch ($type) {
				case 'd':
					$val = self::dintval($source[$k]);
					break;
				case 's':
					$val = self::dstring($source[$k]);
					break;
				case 'f':
					$val = sprintf('%F', $source[$k]);
					break;
				case '':
				default :
					$val = $source[$k];
			}
			if(empty($val) && isset($default)) {
				$val = $default;
			}
			return $val;
		} else if(isset($default)) {
			return $default;
		} else {
			return null;
		}
	}


	/**
	 * 安全的 intval， 可以支持 int(10) unsigned
	 * 支持最大整数 0xFFFFFFFF 4294967295
	 * @param mixed $int string|int|array
	 * @return mixed
	 */
	static public function dintval($int, $allowarray = false) {
		$ret = intval($int);
		if($int == $ret || !$allowarray && is_array($int)) return $ret;
		if($allowarray && is_array($int)) {
			foreach($int as &$v) {
				$v = self::dintval($v, true);
			}
			return $int;
		} elseif($int <= 0xffffffff) {
			$l = strlen($int);
			$m = substr($int, 0, 1) == '-' ? 1 : 0;
			if(($l - $m) === strspn($int,'0987654321', $m)) {
				return $int;
			}
		}
		return $ret;
	}
	
	static public function dstring($str) {
		return htmlspecialchars($str);
	}
	
	public function getAcceptLanguage() {
		if (!$this->_language) {
			$_language = explode(',', $this->getServer('HTTP_ACCEPT_LANGUAGE', ''));
			$this->_language = $_language[0] ? $_language[0] : 'zh-cn';
		}
		return $this->_language;
	}
	
	public function getServerPort() {
		if (!$this->_port) {
			$_default = !strcasecmp($_SERVER['HTTPS'], 'on') ? 443 : 80;
			$this->_port = $_SERVER['SERVER_PORT'] ? $_SERVER['SERVER_PORT'] : $_default;
		}
		return $this->_port;
	}
	
	public function getBaseUrl($absolute = false) {
		if ($this->_baseUrl === null) $this->_baseUrl = rtrim(dirname($this->getScriptUrl()), '\\/.');
		return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
	}
	
	public function getRequestUri() {
		if (!$this->_requestUri) $this->_initRequestUri();
		return $this->_requestUri;
	}
	
	public function getScriptUrl() {
		if (!$this->_scriptUrl) $this->_initScriptUrl();
		return $this->_scriptUrl;
	}
	
	public function getPathInfo() {
		if (!$this->_pathInfo) $this->_initPathInfo();
		return $this->_pathInfo;
	}
	
	public function getMobile() {
		if(!isset($this->_mobile)) $this->_initmobile();
		return $this->_mobile;
	}
	
	public function getAjax() {
		if(!isset($this->_ajax)) $this->_initAjax();
		return $this->_ajax;
	}
	
	private function _initRequestUri() {
		if (($requestUri = $_SERVER['HTTP_X_REWRITE_URL']) != null) {
			$this->_requestUri = $requestUri;
		} elseif (($requestUri = $_SERVER['REQUEST_URI']) != null) {
			$this->_requestUri = $requestUri;
			if (strpos($this->_requestUri, $_SERVER['HTTP_HOST']) !== false) $this->_requestUri = preg_replace(
					'/^\w+:\/\/[^\/]+/', '', $this->_requestUri);
		} elseif (($requestUri = $_SERVER['ORIG_PATH_INFO']) != null) {
			$this->_requestUri = $requestUri;
			if (($query = $_SERVER['QUERY_STRING']) != null) $this->_requestUri .= '?' . $query;
		} else
			throw new Exception(__CLASS__ . ' is unable to determine the request URI.');
	}
	
	private function _initScriptUrl() {
		if (($scriptName = $_SERVER['SCRIPT_FILENAME']) == null) {
			throw new Exception(__CLASS__ . ' determine the entry script URL failed!!!');
		}
		$scriptName = basename($scriptName);
		if (($_scriptName = $_SERVER['SCRIPT_NAME']) != null && basename($_scriptName) === $scriptName) {
			$this->_scriptUrl = $_scriptName;
		} elseif (($_scriptName = $_SERVER['PHP_SELF']) != null && basename($_scriptName) === $scriptName) {
			$this->_scriptUrl = $_scriptName;
		} elseif (($_scriptName = $_SERVER['ORIG_SCRIPT_NAME']) != null && basename($_scriptName) === $scriptName) {
			$this->_scriptUrl = $_scriptName;
		} elseif (($pos = strpos($_SERVER['PHP_SELF'], '/' . $scriptName)) !== false) {
			$this->_scriptUrl = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $scriptName;
		} elseif (($_documentRoot = $_SERVER['DOCUMENT_ROOT']) != null && ($_scriptName = $_SERVER['SCRIPT_FILENAME']) != null && strpos($_scriptName, $_documentRoot) === 0) {
				$this->_scriptUrl = str_replace('\\', '/', str_replace($_documentRoot, '', $_scriptName));
		} else
			throw new Exception(__CLASS__ . ' determine the entry script URL failed!!');
	}
	
	private function _initHostInfo() {
		$http = !strcasecmp($this->getServer('HTTPS'), 'on') ? 'https' : 'http';
		if (($httpHost = $_SERVER['HTTP_HOST']) != null)
			$this->_hostInfo = $http . '://' . $httpHost;
		elseif (($httpHost = $_SERVER['SERVER_NAME']) != null) {
			$this->_hostInfo = $http . '://' . $httpHost;
			if (($port = $this->getServerPort()) != null) $this->_hostInfo .= ':' . $port;
		} else
			throw new Exception(__CLASS__ . ' determine the entry script URL failed!!');
	}
	
	private function _initPathInfo() {
		$requestUri = $this->getRequestUri();
		$scriptUrl = $this->getScriptUrl();
		$baseUrl = $this->getBaseUrl();
		if (strpos($requestUri, $scriptUrl) === 0)
			$pathInfo = substr($requestUri, strlen($scriptUrl));
		elseif ($baseUrl === '' || strpos($requestUri, $baseUrl) === 0)
		$pathInfo = substr($requestUri, strlen($baseUrl));
		elseif (strpos($_SERVER['PHP_SELF'], $scriptUrl) === 0)
		$pathInfo = substr($_SERVER['PHP_SELF'], strlen($scriptUrl));
		else
			throw new Exception(__CLASS__ . ' determine the entry path info failed!!');
		if (($pos = strpos($pathInfo, '?')) !== false) $pathInfo = substr($pathInfo, $pos + 1);
		$this->_pathInfo = trim($pathInfo, '/');
	}
	
	private function _initmobile() {
		static $touchbrowser_list =array('iphone', 'android', 'phone', 'mobile', 'wap', 'netfront', 'java', 'opera mobi', 'opera mini',
				'ucweb', 'windows ce', 'symbian', 'series', 'webos', 'sony', 'blackberry', 'dopod', 'nokia', 'samsung',
				'palmsource', 'xda', 'pieplus', 'meizu', 'midp', 'cldc', 'motorola', 'foma', 'docomo', 'up.browser',
				'up.link', 'blazer', 'helio', 'hosin', 'huawei', 'novarra', 'coolpad', 'webos', 'techfaith', 'palmsource',
				'alcatel', 'amoi', 'ktouch', 'nexian', 'ericsson', 'philips', 'sagem', 'wellcom', 'bunjalloo', 'maui', 'smartphone',
				'iemobile', 'spice', 'bird', 'zte-', 'longcos', 'pantech', 'gionee', 'portalmmm', 'jig browser', 'hiptop',
				'benq', 'haier', '^lct', '320x320', '240x320', '176x220', 'windows phone');
	
		$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
		foreach($touchbrowser_list as $v) {
			if(strpos($useragent, $v) !== false) {
				$this->_mobile = true;
				break;
			}
		}
		$this->_mobile = false;
	}
	
	private function _initAjax() {
		$this->_ajax = empty($_GET['inajax']) ? 0 : (empty(DZF::app()->config['output']['ajaxvalidate']) ? 1 : ($_SERVER['REQUEST_METHOD'] == 'GET' && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' || $_SERVER['REQUEST_METHOD'] == 'POST' ? 1 : 0));
	}
}
